import { ItemCollectionConverter, ItemCollectionEditorComponent } from '@farris/designer-devkit';
import { UniformEditorDataUtil } from '@farris/designer-services';
import { ElementPropertyConfig } from '@farris/ide-property-panel';
import { EditorTypes } from '@farris/ui-datagrid-editors';
import { FormPropertyChangeObject } from '../../../../../lib/entity/property-change-entity';
import { NoCodeInputProps } from '../../common/property/nocode-input-property-config';
export class NoCodeEnumFieldProp extends NoCodeInputProps {

    propertyConfig: ElementPropertyConfig[];


    getPropConfig(propertyData: any): ElementPropertyConfig[] {

        const propertyConfig: ElementPropertyConfig[] = [];

        // 基本信息属性
        const basicPropConfig = this.getBasicPropConfig(propertyData, this.viewModelId);
        propertyConfig.push(basicPropConfig);

        // 外观属性
        const appearanceProperties = this.getAppearancePropConfig(propertyData, this.viewModelId);
        propertyConfig.push(appearanceProperties);

        // 行为属性
        const behaviorPropConfig = this.getBehaviorPropConfig(propertyData, this.viewModelId);
        propertyConfig.push(behaviorPropConfig);

        // 表达式属性
        const exprPropConfig = this.getExpressionPropConfig(propertyData, this.viewModelId);
        if (exprPropConfig) {
            propertyConfig.push(exprPropConfig);
        }

        return propertyConfig;

    }


    private getBehaviorPropConfig(propertyData: any, viewModelId: string, showPosition = 'card'): ElementPropertyConfig {
        const enumDataConfig = this.getEnumDataConfig(propertyData, viewModelId);
        const { maxLength, bindingFieldType } = this.getMaxLengthOfBindingField(propertyData, viewModelId);
        const controlSource = propertyData.controlSource;

        let behaviorProperties = [];
        if (showPosition === 'card' || showPosition === 'tableTdEditor') {
            behaviorProperties = this.getBehaviorCommonPropConfig(propertyData, viewModelId);
        }


        behaviorProperties.push(
            {
                propertyID: 'bindDataSource',
                propertyName: '枚举数据',
                propertyType: 'unity',
                description: '枚举数据设置',
                editorParams: {
                    controlName: UniformEditorDataUtil.getControlName(propertyData),
                    editorOptions: {
                        types: ['variable'],
                        variables: UniformEditorDataUtil.getVariables(viewModelId, this.domService),
                        getVariables: () => UniformEditorDataUtil.getVariables(viewModelId, this.domService),
                        newVariableType: 'Array',
                        newVariablePrefix: ''
                    },
                },
                visible: controlSource === 'Farris' && propertyData.dataSourceType === 'dynamic',
                showClearButton: true
            },
            {
                propertyID: 'enumData',
                propertyName: '枚举数据',
                propertyType: 'modal',
                description: '枚举数据设置',
                editor: ItemCollectionEditorComponent,
                converter: new ItemCollectionConverter(),
                ...enumDataConfig.editorConfig,
                visible: propertyData.dataSourceType === 'static' && (showPosition === 'card' || showPosition === 'tableTdEditor')
            },
            {
                propertyID: 'autoWidth',
                propertyName: '自动宽度',
                propertyType: 'select',
                description: '宽度是否自动调整',
                iterator: [
                    { key: true, value: '是' },
                    { key: false, value: '否' }
                ],
                controlSource: 'Farris',
                visible: controlSource === 'Farris'
            },
            {
                propertyID: 'viewType',
                propertyName: '展示类型',
                propertyType: 'select',
                description: '展示类型选择',
                iterator: [{ key: 'text', value: '文本' }, { key: 'tag', value: '标签' }],
                controlSource: 'Farris',
                visible: controlSource === 'Farris' && propertyData.multiSelect &&
                    (showPosition === 'card' || showPosition === 'tableTdEditor')
            },
            {
                propertyID: 'enableClear',
                propertyName: '启用清除按钮',
                propertyType: 'select',
                description: '是否启用清除按钮',
                iterator: [
                    { key: true, value: '是' },
                    { key: false, value: '否' }
                ],
                controlSource: 'Farris',
                visible: controlSource === 'Farris'
            }
        );

        const self = this;
        const config = {
            categoryId: 'behavior',
            categoryName: '行为',
            properties: behaviorProperties,
            setPropertyRelates(changeObject: FormPropertyChangeObject, data, parameters) {
                self.changeBehaviorPropertyRelates(this.properties, changeObject, propertyData, parameters, showPosition);

                if (!changeObject) {
                    return;
                }
                switch (changeObject && changeObject.propertyID) {
                    case 'multiSelect': {
                        this.properties.map(p => {
                            if (p.propertyID === 'viewType') {
                                p.visible = controlSource === 'Farris' && changeObject.propertyValue && showPosition === 'card';
                            }
                        });
                        break;
                    }
                    case 'enumData': {
                        if (enumDataConfig.dynamicMappingKeys && parameters) {
                            propertyData.idField = parameters.valueField;
                            propertyData.textField = parameters.nameField;
                        }
                        // 枚举同步至schema，在表单保存时同步be vo
                        if (propertyData.binding && propertyData.binding.field) {
                            const fieldInfo = self.schemaService.getFieldByIDAndVMID(propertyData.binding.field, viewModelId);
                            if (fieldInfo && fieldInfo.schemaField) {
                                fieldInfo.schemaField.type.enumValues = changeObject.propertyValue || [];
                            }
                        }

                        break;
                    }
                    case 'dataSourceType': {
                        const enumData = this.properties.find(p => p.propertyID === 'enumData');
                        const bindDataSource = this.properties.find(p => p.propertyID === 'bindDataSource');
                        const idField = this.properties.find(p => p.propertyID === 'idField');
                        const textField = this.properties.find(p => p.propertyID === 'textField');

                        if (enumData) {
                            enumData.visible = changeObject.propertyValue === 'static' && showPosition === 'card';
                        }

                        if (bindDataSource) {
                            bindDataSource.visible = changeObject.propertyValue === 'dynamic';
                        }
                        if (idField) {
                            idField.readonly = changeObject.propertyValue === 'static';
                        }
                        if (textField) {
                            textField.readonly = changeObject.propertyValue === 'static';
                        }

                        break;
                    }
                    case 'noSearch': {
                        const maxSearchLength = this.properties.find(p => p.propertyID === 'maxSearchLength');
                        if (maxSearchLength) {
                            maxSearchLength.visible = changeObject.propertyValue;
                        }
                        break;
                    }
                }
            }

        };
        if (showPosition !== 'card') {
            Object.assign(config, {
                categoryId: showPosition + '_' + config.categoryId,
                propertyData,
                enableCascade: true,
                parentPropertyID: 'editor',
                tabId: showPosition,
                tabName: '编辑器'
            });
        }
        return config;
    }

    /**
     * 列编辑器属性
     * @param gridFieldData 列数据
     */
    getGridFieldEdtiorPropConfig(gridFieldData: any, viewModelId: string) {
        const propertyData = gridFieldData.editor;

        this.propertyConfig = [];

        // 编辑器类型属性
        const editorTypeConfig = this.getGridFieldEditorTypePropertyConfig(gridFieldData, viewModelId);
        if (editorTypeConfig) {
            this.propertyConfig.push(editorTypeConfig);
        }

        // 行为属性
        const behaviorConfig = this.getBehaviorPropConfig(propertyData, viewModelId, 'gridFieldEditor');
        this.appendBehaviorPropsForGridFieldEditor(behaviorConfig, propertyData, viewModelId);
        this.propertyConfig.push(behaviorConfig);

        return this.propertyConfig;
    }


    /**
     * 枚举数据的编辑器不同：
     * kendo的控件确定只有value-name键值
     * farris的控件若绑定了枚举字段只有value-name 键值；若绑定了变量或者字符串字段则可以自行指定idField 和textField
     */
    getEnumDataConfig(propertyData: any, viewModelId: string): { editorConfig: any, dynamicMappingKeys: boolean } {
        if (!propertyData.binding) {
            return { editorConfig: null, dynamicMappingKeys: false };
        }

        const editorConfig: any = {
            editorParams: {
                columns: [
                    { field: 'value', title: '枚举值', editor: { type: EditorTypes.TEXTBOX } },
                    { field: 'name', title: '枚举名称', editor: { type: EditorTypes.TEXTBOX } },
                ],
                requiredFields: ['value', 'name'],
                uniqueFields: ['value', 'name'],
                modalTitle: '枚举编辑器',
                canEmpty: true
            }
        };
        if (propertyData.controlSource !== 'Farris') {
            return { editorConfig, dynamicMappingKeys: false };
        }
        // 绑定枚举字段的 下拉控件，编辑器只支持value-name
        if (propertyData.binding.type === 'Form') {
            const dgVM = this.dgVMService.getDgViewModel(viewModelId);
            const dgVMField = dgVM.fields.find(f => f.id === propertyData.binding.field);
            if (dgVMField.type.name === 'Enum') {
                return { editorConfig, dynamicMappingKeys: false };
            }
        }
        editorConfig.editorParams.dynamicMappingKeys = true;
        editorConfig.editorParams.valueField = propertyData.idField;
        editorConfig.editorParams.nameField = propertyData.textField;

        return { editorConfig, dynamicMappingKeys: true };
    }
    /**
     * 获取绑定字段schema中的长度、类型属性
     */
    private getMaxLengthOfBindingField(propertyData: any, viewModelId: string) {
        let maxLength;
        let bindingFieldType;
        if (propertyData.binding && propertyData.binding.type === 'Form') {
            const fieldInfo = this.schemaService.getFieldByIDAndVMID(propertyData.binding.field, viewModelId);
            if (fieldInfo && fieldInfo.schemaField) {
                maxLength = fieldInfo.schemaField.type.length;
                bindingFieldType = fieldInfo.schemaField.type.name;
            }
        }
        return { maxLength, bindingFieldType };
    }


    /**
     * table单元格编辑器属性
     * @param tdData 单元格数据
     * @param viewModelId viewModelId
     * @returns 属性配置
     */
    getTableTdEdtiorPropConfig(tdData: any, viewModelId: string): ElementPropertyConfig[] {
        const propertyData = tdData.editor;

        this.propertyConfig = [];

        // 外观属性
        const appearanceConfig = this.getAppearancePropConfig(propertyData, viewModelId, 'tableTdEditor');
        this.propertyConfig.push(appearanceConfig);

        // 行为属性
        const behaviorConfig = this.getBehaviorPropConfig(propertyData, viewModelId, 'tableTdEditor');
        behaviorConfig.properties = behaviorConfig.properties.filter(p => !'binding,visible'.includes(p.propertyID));
        this.propertyConfig.push(behaviorConfig);

        // 表达式属性
        const exprPropConfig = this.getExpressionPropConfig(propertyData, viewModelId, 'tableTdEditor');
        if (exprPropConfig) {
            this.propertyConfig.push(exprPropConfig);
        }

        return this.propertyConfig;
    }

}
